<template>
  <a-form-model
    ref="formComp"
    :model="formData"
    :rules="rules"
    layout="horizontal"
    class="AsteriskAfter newEditStyle editVehicleVersion"
  >
    <div class="editVehicleVersionTop">
      <a-row style="height: 32px; overflow: hidden">
        <a-col :md="24" :sm="24">
          <a-form-model-item :label="$t('versionDetail')" class="customFormModelItem"></a-form-model-item>
        </a-col>
      </a-row>
      <a-row :gutter="20">
        <!-- 选择车型 -->
        <a-col :md="12" :sm="24">
          <a-form-model-item :label="$t('vehicleModel')" prop="modelId">
            <car-model-select
              mode="default"
              :query="{ time }"
              :has-all="false"
              :default-value="formData.modelId"
              :disabled="!!id"
              :clear="true"
              @changeoption="changeModelBefore"
              placeholder="vehicleModel"
            ></car-model-select>
          </a-form-model-item>
        </a-col>
        <!-- 车辆版本 -->
        <a-col :md="12" :sm="24">
          <a-form-model-item prop="name">
            <span slot="label">
              {{ $t('smartDrivingDomainVersion') }}
              <question-mark-tip
                :tip-title="versionType === 'TEST' ? $t('inputVersionNameTipForTest') : $t('inputVersionNameTip')"
                :popupContainer="getPopupContainer"
              ></question-mark-tip>
            </span>

            <a-input v-model="formData.name" v-if="versionType === 'TEST'" :disabled="true"/>
            <a-input v-model="formData.name" v-else/>

          </a-form-model-item>
        </a-col>
      </a-row>
      <div class="spaceBox"></div>
      <a-row>
        <a-col :md="24" :sm="24">
          <a-form-model-item :label="$t('ecuVersionConfig')" class="customFormModelItem"></a-form-model-item>
        </a-col>
      </a-row>
    </div>
    <div class="editVehicleVersionConfigBox">
      <ecu-version-config
        :model-id="formData.modelId"
        :id="id"
        :time="nowTime"
        :versionType="versionType"
        :default-versions="defaultSelectedVersions"
        ref="ecuVersionConfigRef"
      ></ecu-version-config>
    </div>
    <!-- 发布说明 -->
    <div class="releaseNoteBox">
      <a-row>
        <a-col :md="24" :sm="24">
          <a-form-model-item :label="$t('releaseNote')" class="customFormModelItem"></a-form-model-item>
        </a-col>
      </a-row>
      <div>
        <a-row>
          <a-col :md="24" :sm="24">
            <!-- 功能新增 -->
            <a-form-model-item :label="$t('funcAdd')" prop="functionAddition">
              <custom-text-area
                @change="handlerChange('functionAddition', $event)"
                :val="formData.functionAddition"
                :max-len="500"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :md="24" :sm="24">
            <!-- 功能优化 -->
            <a-form-model-item :label="$t('funcOptimize')" prop="functionOptimization">
              <custom-text-area
                @change="handlerChange('functionOptimization', $event)"
                :val="formData.functionOptimization"
                :max-len="500"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
      </div>

      <a-row>
        <a-col :md="24" :sm="24">
          <!-- 特别鸣谢 -->
          <a-form-model-item :label="$t('specialThanks')" prop="acknowledgements">
            <custom-text-area
              @change="handlerChange('acknowledgements', $event)"
              :val="formData.acknowledgements"
              :max-len="45"
            ></custom-text-area>
          </a-form-model-item>
        </a-col>
      </a-row>
      <div>
        <a-row>
          <a-col :md="24" :sm="24">
            <!-- 版本声明 -->
            <a-form-model-item style="margin-bottom: 0">
              <template #label>
                <div style="line-height:30px;">
                  {{$t('versionNoDeclaration')}}
                  <a-tooltip placement="top" :getPopupContainer="$commonFun.getPopupContainer"
                    title="添加一段功能描述"
                    v-if="formData.functionDi6Info.functionDi6Infos.length<20"
                  >
                    <a-icon type="plus-circle" style="font-size: 22px;color:#4388A6;cursor: pointer" @click="addFunctionDi6Info"/>
                  </a-tooltip>
                </div>
              </template>
            </a-form-model-item>
            <template v-for="(functionDi6Info, index) in formData.functionDi6Info.functionDi6Infos">
              <a-form-model-item
                :label="''"
                :key="'functionDi6Info-title'+index"
                :prop="'functionDi6Info.functionDi6Infos.' + index + '.functionTitle'"
                :rules="{required: true,message: '功能描述标题不能为空', trigger: 'change',max:23}"
              >
                <a-input :maxLength="23"
                  v-model="functionDi6Info.functionTitle"
                  placeholder="输入功能描述标题......"
                  style="width: 90%; margin-right: 8px"
                />
                <span
                  style="display:inline-block;width: 90px;padding-top:5px;line-height: 32px;vertical-align: middle"
                >
                  <a-tooltip
                    :title="$t('delete')"
                  >
                    <a-icon
                      type="minus-circle"
                      style="font-size: 26px;padding-left:10px;"
                      @click="removeFunctionDi6Info(functionDi6Info)"
                    />
                  </a-tooltip>
                </span>
              </a-form-model-item>
              <a-form-model-item
                :name="['functionDi6Infos', index, 'desc']"
                :key="'functionDi6Info-msg'+index"
                :prop="'functionDi6Info.functionDi6Infos.' + index + '.functionMsg'"
                :rules="{required: true,message: '功能描述不能为空', trigger: 'change',}"
              >
                <custom-text-area
                  placeholder="输入功能描述......"
                  @change="functionDi6Info.functionMsg = $event"
                  :max-len="500"
                  :rows="2"
                  :val="functionDi6Info.functionMsg"
                  style="width: 100%; margin-right: 8px"
                />
              </a-form-model-item>
            </template>
          </a-col>
        </a-row>
      </div>

    </div>
  </a-form-model>
</template>
<script>
import lodash from 'lodash'
import { vehicleVersionInitFormData } from '../config/form'
import CarModelSelect from '@/views/components/CarModelSelect'
import EcuVersionConfig from './EcuVersionConfig'
import QuestionMarkTip from '@/views/components/QuestionMarkTip'
import LangSelect from '@/views/components/LangSelect'
import IsEnabledSelect from '@/views/components/IsEnabledSelect'
import CustomTextArea from '@/components/CustomTextArea/index.vue'
import moment from 'moment'
import { checkTextLen, checkVersionName } from '@/utils/validate'
import vehicleVersionApi from '@/api/modules/software/vehicleVersion'
export default {
  components: {
    CarModelSelect,
    EcuVersionConfig,
    QuestionMarkTip,
    LangSelect,
    IsEnabledSelect,
    CustomTextArea
  },
  props: {
    time: {
      type: Number,
      default: 456120
    },
    // 车辆版本id
    id: {
      type: String,
      default: ''
    },
    versionType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      formData: lodash.cloneDeep(vehicleVersionInitFormData),
      rules: {
        modelId: [{ required: true, message: this.$t('pleaseSelect') }],
        name: [
          { required: true, message: this.$t('pleaseInput') },
          {
            validator: checkVersionName(this.versionType)
          }
        ],
        code: [
          { required: true, message: this.$t('pleaseInput') },
          {
            validator: (rule, value, callback) => {
              if (!/^\d+$/.test(value)) {
                callback(new Error(this.$t('onlyInputNumber')))
                return
              }
              callback()
            }
          }
        ],
        enabled: [{ required: true, message: this.$t('pleaseInput') }],
        functionDi6Info: {
          functionOne: [{ required: true, message: this.$t('pleaseInput') }],
          functionTwo: [{ required: true, message: this.$t('pleaseInput') }]
        },
        description: [{ required: true, message: this.$t('pleaseInput') }, { validator: checkTextLen(500, true) }],
        functionAddition: [{ required: true, message: this.$t('pleaseInput') }, { validator: checkTextLen(500, true) }],
        functionOptimization: [
          { required: true, message: this.$t('pleaseInput') },
          { validator: checkTextLen(500, true) }
        ],
        acknowledgements: [{ validator: checkTextLen(45) }]
      },
      nowTime: Date.now(),
      loadingDetail: false,
      // 默认已选中的零件配置
      defaultSelectedVersions: null,
      activeDiTab: 'DI6',
      diError: {
        di5: false,
        di6: false
      },
    }
  },
  watch: {
    time: {
      handler(val) {
        // this.resetFormData()
        this.nowTime = val
        this.init();
      },
      immediate: true
    },
  },
  computed:{
    hasAll5(){
      if(this.formData.functionAddition!=''&&this.formData.functionOptimization!=''){
        return this.diError.di5=false
      }else{
         return this.diError.di5=true
      }
    },
    hasAll6(){
       let isAll=this.isAllfunctionDi6Infos(this.formData.functionDi6Info.functionDi6Infos)
      if(this.formData.functionDi6Info.functionOne!=''&&this.formData.functionDi6Info.functionTwo!=''&&isAll){
          return this.diError.di6=false
      }else{
         return this.diError.di6=true
      }
    }

  },
  created() {
    this.resetFormData()
    this.init()
    this.initTestVehicleVersion()
  },
  methods: {
    init() {
      if (!this.id) {
        this.formData.code = moment(new Date()).format('YYYYMMDDHHmmss')
      } else {
        this.getDetailData()
      }
    },
    isAllfunctionDi6Infos(arr){
     return arr.every(item=>{
        if(item.functionTitle!=''&&item.functionMsg!=''){
          return true
        }else{
          return false
        }
      })

    },
    addFunctionDi6Info() {
      if (this.formData.functionDi6Info.functionDi6Infos.length > 20) {
        this.$message.warn('功能描述不能超过20项！')
      }
      this.formData.functionDi6Info.functionDi6Infos.push({
        functionMsg: '',
        functionTitle: ''
      })
    },
    removeFunctionDi6Info(item) {
      let index = this.formData.functionDi6Info.functionDi6Infos.indexOf(item)
      if (index !== -1) {
        this.formData.functionDi6Info.functionDi6Infos.splice(index, 1)
      }
    },
    handlerChange(key, val) {
      this.formData[key] = val
    },
    getPopupContainer() {
      return document.body
    },
    changeModelBefore(val) {
      const _this = this
      const configData = this.$refs.ecuVersionConfigRef.getConfigData()
      if (configData.length === 0) {
        this.changeModel(val)
        return
      }
      this.$confirm({
        title: _this.$t('systemTip'),
        content: _this.$t('addVehicleVersionChangeModelTip'),
        onOk() {
          _this.changeModel(val)
          _this.defaultSelectedVersions = null
        },
        onCancel() {}
      })
    },
    changeModel(val) {
      this.formData.modelId = val
      this.$nextTick(() => {
        this.$refs.formComp.validateField('modelId')
      })
      this.nowTime = Date.now()
    },
    openNotification(old, newOne) {
      const key = `open${Date.now()}`;
      this.$notification.open({
        message: '提示',
        description:
          '智驾域版本号'+old+'已过期, 系统自动重新生成' + newOne,
        btn: h => {
          return h(
            'a-button',
            {
              props: {
                type: 'primary',
                size: 'small',
              },
              on: {
                click: () => this.$notification.close(key),
              },
            },
            '确认',
          );
        },
        key
      });
    },
    getDetailData() {
      this.loadingDetail = true
      this.$store
        .dispatch('getVehicleVersionDetailData', { id: this.id, versionType: this.versionType })
        .then(res => {
          const data = res.data
          if (data) {
            this.formData.modelId = data.modelId
            this.formData.name = data.name;
            this.formData.code = data.code
            this.formData.id = data.id
            this.formData.enabled = data.enabled
            this.formData.description = data.description
            this.formData.functionAddition = data.functionAddition
            this.formData.functionOptimization = data.functionOptimization
            this.formData.acknowledgements = data.acknowledgements
            // if (data.functionDi6Info && data.functionDi6Info.functionInfo) {
            //   data.functionDi6Info.functionDi6Infos = data.functionDi6Info.functionInfo;
            // }
            this.formData.functionDi6Info =
              data.functionDi6Info || lodash.cloneDeep(vehicleVersionInitFormData.functionDi6Info)
            if (
              !this.formData.functionDi6Info.functionDi6Infos ||
              this.formData.functionDi6Info.functionDi6Infos.length === 0
            ) {
              this.formData.functionDi6Info.functionDi6Infos = [
                ...vehicleVersionInitFormData.functionDi6Info.functionDi6Infos
              ]
            }
            this.nowTime = Date.now()
            const ecuVersions = {}
            data.ecuVersions.forEach(version => {
              ecuVersions[version.ecuId] = {
                versionId: version.versionId,
                versionName: version.version.name,
                versionType: version.version.versionType,
                groupRollback: version.groupRollback,
                groupNo: version.groupNo,
                groupUpgradeNo: version.groupUpgradeNo,
                releaseNotes: version.releaseNotes || [],
                configVersionName: version.configVersionName
              }
            })
            this.defaultSelectedVersions = ecuVersions
          }
        })
        .finally(() => {
          this.loadingDetail = false
        })
    },
    // 获取表单中的数据
    getFormData() {
      const thisWeb = this

      return new Promise((resolve, reject) => {
        const data = {...this.formData}
        this.$refs.formComp.validate((valid, errors) => {
          this.diError.di6 = false
          this.diError.di5 = false
          if (!valid) {
            for (const key in errors) {
              if (key.indexOf('functionDi6Info') === 0) {
                this.diError.di6 = true
              } else if (key === 'functionAddition' || key === 'functionOptimization') {
                this.diError.di5 = true
              }
            }
            reject(valid)
            return
          }
          let configData = this.$refs.ecuVersionConfigRef.getConfigData()
          if (!this.otherCheck(configData)) {
            reject(new Error(this.$t('pleaseInput') + this.$t('ecuVersion')).toLowerCase())
            return
          }
          if (this.id && !this.$refs.ecuVersionConfigRef.checkConfigIsDiff(configData)) {
            // 是编辑的时候且零件配置信息没有变化的时候后端要求传递[]
            configData = []
          }
          data.name = data.name;
          data.ecuVersions = configData
          data.versionType = this.versionType;
          if(!this.id && this.versionType === 'TEST'){
            thisWeb.$api.getNextVehicleVersion().then(res=>{
                if(res.code == 0){
                  console.info(res.data)
                  const old = thisWeb.formData.name
                  // 因为测试智驾域版本号是自动生成的，在提交前进行再次获取最新
                  thisWeb.formData.name = res.data
                  const newOne = thisWeb.formData.name
                  if(old != newOne){
                    this.openNotification(old, newOne)
                    return
                  }
                  resolve(data);
                }else{
                  reject(new Error('无法查询最新可用版本号'))
                  return
                }
              })
          }else{
            resolve(data)
          }
        })
      })
    },
    otherCheck(configData) {
      if (configData.length === 0) {
        const msg = this.$t('pleaseSelect') + this.$t('ecuVersion').toLowerCase()
        this.$message.error(msg)
        return false
      }
      return true
    },
    resetFormData() {
      this.formData = lodash.cloneDeep(vehicleVersionInitFormData)
      this.defaultSelectedVersions = null
      this.releaseNotes = []
      this.$refs.formComp && this.$refs.formComp.resetFields()
      this.$refs.ecuVersionConfigRef && this.$refs.ecuVersionConfigRef.resetData()
    },
    // 调用后台接口，生成最新的测试域版本号
    initTestVehicleVersion(){
      if(!this.id && this.versionType === 'TEST'){
        this.$api.getNextVehicleVersion().then(res=>{
          if(res.code == 0){
            this.formData.name = res.data;
          }
        })
      }
    }
  }
}
</script>
<style scoped lang="less">
.iconWrap {
  width: 32px;
  height: 32px;
  text-align: center;
  border: 1px solid rgb(242, 242, 242);
  border-radius: @border-radius-base;
  margin-top: 4px;
  line-height: 32px;
  cursor: pointer;
}
.editVehicleVersion {
  display: flex;
  flex-direction: column;
  .editVehicleVersionTop {
    flex: none;
  }
  .spaceBox {
    height: 10px;
    border-bottom: 1px solid @borderColor;
    margin-bottom: 20px;
  }
  .releaseNoteBox {
    margin: 20px 0;
  }
}
.btn-tab {
  .ant-btn.active {
    background-color: #4da6cd;
    color: white;
  }
  .ant-btn.error {
    border-color: red;
  }
}
</style>
